// @ts-nocheck
import React, { Component } from "react";
import { Input, Button, Toast } from "antd-mobile";
import AMapLoader from "@amap/amap-jsapi-loader";
import { Link } from "react-router-dom";
import { Map_Key } from "@/utils/config";
import { pointSearch } from "./service";
import gcoord from "gcoord";
import { useNavigate } from "react-router-dom";
import "./index.less";
export interface IAddressItem {
  city?: string; //市
  district?: string; //区
  township?: string; // 街道 社区
  street?: string; //路
  contry?: string; //门牌号
  hadress: string; //详细地址
  longitude: number; //经度
  latitude: number; //纬度
}

interface IState {
  value: string;
  address: string;
  formItem: {
    content?: string;
    addressDetailedUser?: string;
    type?: string[];
    fileFront?: string;
    address?: string;
    title?: string;
  };
  addressItem: IAddressItem;
}

type IProps = {};

const DEFALTE_ADDRESS: IAddressItem = {
  hadress: "", //详细地址
  longitude: -1, //经度
  latitude: -1, //纬度
};

class MapComponent extends Component<IProps, IState> {
  map: {};
  marker: any;
  geocoder: any;
  geolocation: any;
  cityCode: string | null;
  current: any;
  placeSearch: any;
  auto: any;
  heaf: string;
  constructor() {
    console.log(window.location);

    super();
    this.map = {};
    this.marker = null;
    this.geocoder = null;
    this.geolocation = null;
    this.cityCode = "028";
    this.current = null;
    this.placeSearch = null;
    this.auto = null;
    this.heaf = "";
    this.state = {
      value: "",
      address: "",
      formItem: {},
      addressItem: DEFALTE_ADDRESS,
      pointInfo: {},
      isPoint: false,
      back: window.location.search.split("=")[2],
      url: window.location.search.split("=")[1],
    };
  }


  // 2.dom渲染成功后进行map对象的创建
  componentDidMount() {
    this.heaf = window.location.search.split("=")[1];
    AMapLoader.load({
      key: Map_Key, // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: [
        "AMap.Geocoder",
        "AMap.PlaceSearch",
        "AMap.AutoComplete",
        "AMap.Marker",
        "AMap.Geolocation",
      ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    })
      .then((AMap) => {
        const that = this;
        this.map = new AMap.Map("container", {
          zoom: 15,
          resizeEnable: true,
          center: [106.63, 30.46],
          // center: [104.07, 30.57],
        });
        // this.map.setCity("简阳市");
        this.map.getCity((result) => {
          {
            that.cityCode = result.citycode;
            that.placeSearch.setCity(result.citycode);
            that.auto.setCity(result.citycode);
          }
        });

        this.current = Toast.show({
          icon: "loading",
          content: "定位中…",
          duration: 0,
        });
        this.geolocation = new AMap.Geolocation({
          convert: true,
          enableHighAccuracy: true,
          timeout: 10000, // 10秒钟超时
          maximumAge: 1000 * 60 * 5,
          showMarker: true,
          panToLocation: true,
          zoomToAccuracy: true,
          GeoLocationFirst: true,
          getCityWhenFail: true,
          needAddress: true,
          useNative: true,
        });

        this.map.addControl(this.geolocation);
        this.geolocation.getCurrentPosition(this.getCurrentPosition);

        this.geocoder = new AMap.Geocoder();
        this.marker = new AMap.Marker();
        var autoOptions = {
          input: "tipinput",
        };

        this.auto = new AMap.AutoComplete(autoOptions);
        this.placeSearch = new AMap.PlaceSearch({
          map: that.map,
        }); //构造地点查询类
        function select(e) {
          that.setState({ value: e.poi.name });
          that.placeSearch.search(e.poi.name); //关键字查询查询
        }
        this.placeSearch.on("markerClick", this.markClickCallBack);
        this.auto.on("select", select); //注册监听，当选中某条记录时会触发
        this.map.on("movestart", function () {
          that.map.off("dragging", that.draggingClic);
        });
        this.map.on("moveend", function () {
          that.map.on("dragging", that.draggingClic);
        });
        // this.map.on('dragging', draggingClic);
      })
      .catch((e) => {
        console.error(e);
      });
    let formItem = JSON.parse(
      localStorage.getItem("form") || JSON.stringify("")
    );
    localStorage.removeItem("form");
    this.setState({ ...this.state, formItem });
  }

  componentWillUnmount(): void {
    Toast.clear();
  }

  markClickCallBack = (event) => {
    const that = this;
    const { data } = event || {};
    const address: IAddressItem = {
      longitude: data?.location?.lng || data.longitude,
      latitude: data?.location?.lat || data.latitude,
      hadress: data.name,
    };
    this.geocoder.getAddress(
      [address.longitude, address.latitude],
      function (status, result) {
        if (status === "complete") {
          //保存地址信息
          const {
            regeocode: { addressComponent },
          } = result;
          address.city = addressComponent.city;
          address.district = addressComponent.district;
          address.township = addressComponent.township;
          address.street = addressComponent.street;
          address.contry = addressComponent.streetNumber;
        }
        if (data.longitude && data.latitude) {
          that.setState({ pointInfo: data });
        }
        that.setState({
          ...that.state,
          address: result.regeocode.formattedAddress,
          value: data.name,
          addressItem: address,
        });
      }
    );
  };
  draggingClic = (e) => {
    const that = this;
    var lat = e.lnglat.lat;
    var lng = e.lnglat.lng;
    that.geocoder.getAddress([lng, lat], function (status, result) {
      const address: IAddressItem = DEFALTE_ADDRESS;
      if (status === "complete") {
        //保存地址信息
        const {
          regeocode: { addressComponent },
        } = result;
        address.city = addressComponent.city;
        address.district = addressComponent.district;
        address.township = addressComponent.township;
        address.street = addressComponent.street;
        address.contry = addressComponent.streetNumber;
      }
      that.marker.setPosition(e.lnglat);
      that.map.add(that.marker);
      // that.map.setFitView(that.marker);
      that.setState({
        ...that.state,
        address: result.regeocode?.formattedAddress,
        value: result.regeocode?.formattedAddress,
        addressItem: address,
      });
    });
  };
  handleSearch = () => {
    let that = this;
    this.geocoder.setCity(this.cityCode);
    this.geocoder.getLocation(this.state.value, function (status, result) {
      if (status === "complete" && result.geocodes.length) {
        const data = result.geocodes[0];
        const lnglat = data.location;
        that.marker.setPosition(lnglat);
        pointSearch({ lng: lnglat.lng, lat: lnglat.lat }).then((res) => {
          if (res.code == 200 && res.data.length > 0) {
            let markers = [];
            res.data.forEach((item) => {
              const marker = new AMap.Marker({
                position: [item.longitude, item.latitude],
                icon: new AMap.Icon({
                  image: "/assets/markerEvent.png",
                  size: new AMap.Size(50, 58.33333),
                  imageSize: new AMap.Size(50, 58.33333),
                }),
                zIndex: 100,
              });
              marker.setLabel({
                content: item.name,
                direction: "top", //设置文本标注方位
              });
              marker.moveTo([item.longitude, item.latitude], 300);
              marker.on("click", () => {
                const params = {
                  data: { ...item, name: item.name },
                };
                that.setState({ isPoint: true });
                that.markClickCallBack(params);
              });
              markers.push(marker);
              that.map.add(marker);
            });

            that.map.setFitView(markers);
          } else {
            that.marker.setLabel({
              content: data.formattedAddress,
              address: data.formattedAddress,
            });
            // 给marker添加点击事件
            that.marker.on("click", () => {
              const params = {
                data: { ...data, name: data.formattedAddress },
              };
              that.markClickCallBack(params);
            });
            const addressItem = {
              longitude: lnglat.lng,
              latitude: lnglat.lat,
            };
            that.map.add(that.marker);
            that.map.setFitView(that.marker);
            that.setState({
              ...that.state,
              address: data.formattedAddress,
              addressItem,
              isPoint: false,
            });
          }
        });
      } else {
        Toast.show({
          icon: "fail",
          content: "根据地址查询位置失败",
        });
      }
    });
  };

  getCurrentPosition = (status: "complete" | "error", resulet: any) => {
    const that = this;
    const address: IAddressItem = DEFALTE_ADDRESS;
    if (status === "complete") {
      const position =
        resulet.location_type === "html5"
          ? [resulet.position.lng, resulet.position.lat]
          : resulet.position;
      address.longitude = position[0];
      address.latitude = position[1];
      this.geocoder.getAddress(position, async function (curStatus, res) {
        if (curStatus === "complete") {
          Toast.clear();
          let data = await res;
          //保存地址信息
          const {
            regeocode: { addressComponent },
          } = data;

          address.city = addressComponent.city;
          address.district = addressComponent.district;
          address.township = addressComponent.township;
          address.street = addressComponent.street;
          address.contry = addressComponent.streetNumber;
          address.hadress = addressComponent.neighborhood;
          that.cityCode = res.citycode;
          that.setState({
            ...that.state,
            value: data.regeocode.addressComponent.neighborhood,
            address: data.regeocode.formattedAddress,
            addressItem: address,
          });
          that.marker.setPosition(resulet.position);
          that.marker.setLabel({
            content: data.regeocode.addressComponent.neighborhood,
            address: data.regeocode.formattedAddress,
          });
          that.map.add(that.marker);
          that.map.setFitView(that.marker);
        } else {
          const center = new AMap.LngLat(106.63, 30.46);
          that.map.setCenter(center);
          that.map.setZoom(15);
          Toast.show({
            icon: "fail",
            content: "获取定位失败,请手动搜索1",
          });
        }
      });
    } else {
      const center = new AMap.LngLat(106.63, 30.46);
      that.map.setCenter(center);
      that.map.setZoom(15);
      Toast.show({
        icon: "fail",
        content: "获取定位失败,请手动搜索2",
      });
    }
  };
  getUrl = () => {
    const { url, isPoint, back } = this.state;
    let newUrl = "";
    if (url == "eventReport") {
      newUrl = "/eventReport";
    } else if (url == "emergencyReporting") {
      newUrl = "/emergencyReporting";
    } else if (url?.indexOf("communityServiceReport") !== -1) {
      // console.log(url);
      newUrl = `/${window.location.search.split("=")[1]}`;
    } else {
      newUrl = `/pointManagement/add?isPoint=${isPoint}&back=${back}`;
    }
    return newUrl;
  };
  handleCancel = () => {
    const formItem = !!this.state.formItem ? this.state.formItem : {};
    const addressItem = {};
    localStorage.setItem("form", JSON.stringify(formItem));
    localStorage.setItem("address", JSON.stringify(addressItem));
  };
  handleOk = () => {
    const formItem = !!this.state.formItem ? this.state.formItem : {};
    const addressItem = !!this.state.addressItem ? this.state.addressItem : {};
    const pointInfo = !!this.state.pointInfo ? this.state.pointInfo : {};
    formItem.address = this.state.value;
    formItem.addressDetailedUser = this.state.address;
    // formItem.type = [pointInfo.type];
    const newFormItem = { ...pointInfo, ...formItem };

    if (addressItem.longitude && addressItem.latitude) {
      const newLnglat = gcoord.transform(
        [addressItem.longitude, addressItem.latitude],
        gcoord.GCJ02,
        gcoord.WGS84
      );
      addressItem.longitude = newLnglat[0];
      addressItem.latitude = newLnglat[1];
    }

    localStorage.setItem("pointInfo", JSON.stringify(pointInfo));
    localStorage.setItem("form", JSON.stringify(newFormItem));
    localStorage.setItem("address", JSON.stringify(addressItem));
  };

  render() {
    // 1.初始化创建地图容器,div标签作为地图容器，同时为该div指定id属性；
    return (
      <>
        <div id="container" className="map" style={{ height: "100vh" }}></div>
        <div className="back">
          <Link to={this.getUrl()}>
            <Button
              style={{ fontSize: 10 }}
              color="primary"
              fill="solid"
              onClick={this.handleCancel}
            >
              返回
            </Button>
          </Link>
        </div>
        <div className="submit">
          <Link to={this.getUrl()}>
            <Button
              style={{ fontSize: 10 }}
              color="primary"
              fill="solid"
              onClick={this.handleOk}
            >
              确定
            </Button>
          </Link>
        </div>
        <div
          style={{
            position: "fixed",
            bottom: "8vh",
            left: "0vw",
            right: "0vw",
            display: "flex",
            justifyContent: "center",
          }}
        >
          <Input
            id="tipinput"
            style={{
              width: "80vw",
              height: "5vh",
              backgroundColor: "white",
              paddingLeft: 10,
            }}
            className="input"
            placeholder="请输入想要搜索的地址"
            value={this.state.value}
            clearable
            onChange={(val: string) => {
              this.setState({ ...this.state, value: val });
            }}
          />
          <Button
            color="primary"
            fill="solid"
            onClick={this.handleSearch}
            style={{ height: "5vh" }}
          >
            搜索
          </Button>
        </div>
      </>
    );
  }
}
//导出地图组建类
export default MapComponent;
